import { useLoadStore } from '@/store/loading'
import { useUserStore } from '@/store/user'

const BASE_URL = import.meta.env.VITE_REQUEST_BASE_URL
const WHITE_API = [] /** 不需要token的接口 */

const request = (config, show = true) => {
  const storeLoading = useLoadStore()
  const userStore = useUserStore()

  const token = uni.getStorageSync('token')
  const header = { 'Content-Type': 'application/json;charset=UTF-8' } // 默认的请求header
  !WHITE_API.includes(config.url) && !!token && (header.token = token)

  config.url = BASE_URL + config.url
  config.method = 'POST' // 统一接口调用方法为post

  return new Promise((resolve, reject) => {
    // config.method === 'GET' &&
    //     (storeLoading.loading.get = true) &&
    //     storeLoading.loading.requestingsGet.push(config.url)
    config.method === 'POST' &&
      (storeLoading.loading.post = true) &&
      storeLoading.loading.requestingsPost.push(config.url)

    uni.request({
      timeout: 60000,
      header,
      ...config,
      success(res) {
        // HTTP 状态码：200状态码表示成功
        if (res.statusCode === 200) {
          const { code, msg, data } = res.data
          if (code !== 10000) {
            show &&
              uni.showToast({
                title: msg,
                icon: 'none',
                duration: 1800
              })
            const INVALID_STATUS_CODE = [10006, 10007, 10010, 10011, 10013]
            if (INVALID_STATUS_CODE.includes(code)) {
              userStore.logout()
              // setTimeout(() => {
              //     uni.reLaunch({ url: '/pages/home/home' })
              // }, 500)
            }
            reject(res.data)
          }
          resolve(data)
        } else {
          uni.showToast({
            title: '接口请求异常',
            icon: 'none'
          })
          reject(res.data)
        }
      },
      fail(err) {
        uni.showToast({
          title: err.errMsg,
          icon: 'none'
        })
        reject(err)
      },
      complete() {
        // 移除已请求完毕的get请求
        // storeLoading.loading.requestingsGet.splice(
        //     storeLoading.loading.requestingsGet.findIndex((i) => i === config.url),
        //     1
        // )
        // storeLoading.loading.get = !!storeLoading.loading.requestingsGet.length

        // 移除已请求完毕的post请求
        storeLoading.loading.requestingsPost.splice(
          storeLoading.loading.requestingsPost.findIndex(i => i === config.url),
          1
        )
        storeLoading.loading.post =
          !!storeLoading.loading.requestingsPost.length
      }
    })
  })
}

export default request
